package com.atzon.controller;

import com.atzon.constant.Const;
import com.atzon.model.User;
import com.atzon.service.UserService;
import com.atzon.service.impl.UserSrviceImpl;
import com.atzon.utils.MailUtil;
import com.atzon.utils.StrUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {
    private UserService userService = new UserSrviceImpl();

    public void login(HttpServletRequest req, HttpServletResponse resp) {
        String name = req.getParameter("form-username");
        String pass = req.getParameter("form-password");
        String check = req.getParameter("form-remember");
        try {
            User user = userService.findUserByName(name);
            if (user != null) {
                if (user.getPassword().equals(pass)) {
                    if (check != null) {
                        Cookie cookie = new Cookie("userInfo", name);
                        cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    Date now = new Date();
                    userService.reLogin(now, user.getId());
                    req.getSession().setAttribute("userId", user.getId());
                    Map<String, Object> map = userService.findUserBaseById(user.getId());
                    req.getSession().setAttribute("userBaseInfo", map);
                    req.getSession().setMaxInactiveInterval(Const.MAX_SESSION_TIME);
                    resp.sendRedirect(req.getContextPath() + "/view/home");
                    return;
                }
            }
            req.getSession().setMaxInactiveInterval(0);
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void Logout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Cookie[] cookies = req.getCookies();
            if (null != cookies && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if ("userInfo".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                        break;
                    }
                }
            }
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void register(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("form-email");
            String name = req.getParameter("form-username");
            String pass = req.getParameter("form-password");
            String repass = req.getParameter("form-password2");
            User userByEmail = userService.findUserByEmail(email);
            User userByName = userService.findUserByName(name);
            if (userByEmail == null && userByName == null) {
                if (pass.equals(repass)) {
                    User user = new User(null, name, pass, "0", email, null);
                    Integer newId = userService.addUser(user);
                    Map<String, Object> map = userService.findUserBaseById(newId);
                    req.getSession().setAttribute("userBaseInfo", map);
                    resp.sendRedirect(req.getContextPath() + "/view/home");
                    return;
                }
            }
            resp.sendRedirect(req.getContextPath() + "/register.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String valid = StrUtil.createRandomNum();
            String to = req.getParameter("email");
            if (StrUtil.checkEmail(to)) {
                String subject = "验证码";
                String charset = "utf-8";
                MailUtil.send(to, subject, valid, charset);
                req.getSession().setAttribute("email-v", valid);
                req.getSession().setMaxInactiveInterval(Const.MAX_CODE_TIME);
            } else {
                resp.sendRedirect(req.getContextPath() + "/forget.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void resetPass(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("form-email");
            String userValid = req.getParameter("form-valid");
            String newPass = req.getParameter("form-password");
            String valid = req.getSession().getAttribute("email-v").toString();
            if(valid != null){
                if (userValid.equals(valid)) {
                    userService.repassword(newPass, email);
                }
            }
            resp.sendRedirect(req.getContextPath() + "/index.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}